/*
 * Copyright 2008 The Microlog project @sourceforge.net
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.sf.microlog.midp.appender.s3;


import com.amazonaws.crypto.Base64;
import com.amazonaws.s3.S3;

/**
 * This is the default S3 log service for Microlog.
 * 
 * It uses the "J2ME and J2SE Toolkit for Amazon S3" found at
 * http://developer.amazonwebservices.com/ .
 * 
 * @author Johan Karlsson (johan.karlsson@jayway.se)
 */
public class S3SOAPLogService implements S3LogService {

	private String accessKeyID = "";
	private String secretAccessKey = "";
	private String logBucket = "microlog";

	private S3 s3;

	/**
	 * Set the access key ID for your Amazon Web Service (AWS) account.
	 * 
	 * @param accessKeyID
	 *            the access key id to use.
	 */
	public void setAccessKeyID(String accessKeyID)
			throws IllegalArgumentException {
		if (accessKeyID != null) {
			this.accessKeyID = accessKeyID;
		} else {
			throw new IllegalArgumentException(
					"The accessKeyID must not be null.");
		}
	}

	/**
	 * Set the secret access key for your Amazon Web Service (AWS) account.
	 * 
	 * @param secretAccessKey
	 *            the access key to use.
	 */
	public void setSecretAccessKey(String secretAccessKey) {
		if (secretAccessKey != null) {
			this.secretAccessKey = secretAccessKey;
		} else {
			throw new IllegalArgumentException(
					"The secretAccessKey must not be null.");
		}
	}

	/**
	 * Store the data on S3 with specified name.
	 * 
	 * @see net.sf.microlog.midp.appender.s3.S3LogService#storeLog(java.lang.String, byte[])
	 */
	public synchronized void storeLog(String name, byte[] data) {

		if (name != null && data != null) {
			init();
			try {
				byte[] encodedData = Base64.encode(data);
				String encodedString = new String(encodedData);
				s3.putObjectInline(logBucket, name, encodedString);
			} catch (Exception e) {
				System.err.println("Failed to put object on S3 server. " + e);
			}

		} else {
			throw new IllegalArgumentException(
					"The name & data must not be null.");
		}
	}

	/**
	 * Do the initialization of the S3 stuff.
	 */
	private void init() {
		if (s3 == null) {
			s3 = new S3(S3.HTTPS_URL, accessKeyID, secretAccessKey);
		}

		try {
			s3.createBucket(logBucket);
		} catch (Exception e) {
			System.err.println("Bucket already exists? " + e);
		}

	}
}
